package com.jereh.fuckmylife.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jereh.fuckmylife.R;
import com.jereh.fuckmylife.adapter.FragmentViewPagerAdapter;
import com.jereh.fuckmylife.fragment.LiveFragment;
import com.jereh.fuckmylife.fragment.MessageFragment;
import com.jereh.fuckmylife.fragment.MineFragment;
import com.jereh.fuckmylife.fragment.QiuShiFragment;
import com.jereh.fuckmylife.fragment.QiuYouCircleFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * 主界面
 */
public class MainActivity extends AppCompatActivity {

    private TabLayout tab;
    private ViewPager pager;
    private List<Fragment> list=new ArrayList<>();
    private FragmentViewPagerAdapter adapter;
    private String[] tab_name={"糗事","糗友圈","直播","小纸条","我"};
    private int[] tab_icon={R.drawable.bottom_tab_icon_qiushi,
            R.drawable.bottom_tab_icon_qiuyoucircle,
            R.drawable.bottom_tab_icon_live,R.drawable.bottom_tab_icon_message,
            R.drawable.bottom_tab_icon_mine};

    //smy的更改
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tab=(TabLayout)findViewById(R.id.tab);
        pager=(ViewPager)findViewById(R.id.pager);
        initView();
    }

    private void initView() {

        //集合里添加fragment
        list.add(new QiuShiFragment());
        list.add(new QiuYouCircleFragment());
        list.add(new LiveFragment());
        list.add(new MessageFragment());
        list.add(new MineFragment());
        //绑定适配器
        adapter=new FragmentViewPagerAdapter(getSupportFragmentManager(),list);
        pager.setAdapter(adapter);
        //绑定选项卡跟viewpager
        tab.setupWithViewPager(pager);
        initUpIcons();
    }

    /**
     * 初始化选项卡
     */
    private void initUpIcons() {
        for (int i=0;i<tab_name.length;i++){
            tab.getTabAt(i).setCustomView(getTabView(i));
        }
    }

    /**
     * 创建选项卡布局
     * @param position
     * @return
     */
    public View getTabView(int position){
        //首先为子tab布置一个布局
        View v = LayoutInflater.from(this).inflate(R.layout.bottom_tab_layout,null);
        TextView name = (TextView) v.findViewById(R.id.name);
        name.setText(tab_name[position]);
        ImageView icon = (ImageView) v.findViewById(R.id.icon);
        icon.setImageResource(tab_icon[position]);
        return v;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pager.removeAllViews();
    }
}
